import regeneratorRuntime, { async } from '../utils/runtime'
import { C } from '../utils/util'
/**
 * 封封微信的的request
 */
import util from '../utils/util'
let cf = {
    LOCAL_TOKEN: 'token',
    PREFIX: '/lms/v1',
    baseUrl: C.fileBaseUrl,
    baseAuth: 'Basic bW9iaWxld2ViLWNsaWVudDpoZ2o='
}

export const wxAsyncWrap = fn => (options = {}) => new Promise((resolve, reject) => {
    let conf = {
        success: res => {
            resolve(res)
        },
        fail: err => {
            if (err.errMsg) {
                util.showMsg(err.errMsg)
            }
            reject(err)
        }
    }

    conf = Object.assign(conf, options)
    wx[fn](conf)
})

const requestAsync = (options = {}) => {
    return new Promise((resolve, reject) => {
        let conf = {
            header: {
                // 'X-Bmob-Application-Id': bmobConfig.applicationId,
                // 'X-Bmob-REST-API-Key': bmobConfig.restApiKey,
                'Content-Type': 'application/json'
            }, // 设置请求的 header
            success: res => {
                // wx.hideLoading()
                const result = res.data
                // console.log('shenmgui ?', result)
                resolve(result)
            },
            fail: err => {
                // wx.hideLoading()
                util.showMsg('出错啦！请稍后再试试哦～')
                console.log('有错误啊,', err)
                reject(err)
            },
            complete: (status, xhr, err) => {
                wx.hideLoading()
                if (status.statusCode === 401) {
                    wx.clearStorageSync()
                }
            }
        }
        conf = Object.assign(conf, options)
        wx.request(conf)
    })
}

// 验证token是否过期
const isValidToken = (data, name) => {
    if (!data || !data[name] || !data.expires_in) {
        return false
    }
    const expiresIn = data.expires_in
    const now = (new Date().getTime())
    return now < expiresIn;
}

export const checkToken = (cb) => {
    let token = util.session(cf.LOCAL_TOKEN)
    // token不存在或已过期
    if (!isValidToken(token, 'access_token')) {
        getToken().then((res) => {
            typeof cb == "function" && cb(res)
        })
    } else {
        typeof cb == "function" && cb(token)
    }
}




const getToken = () => {
    return new Promise((resolve, reject) => {
        return wxAsyncWrap('request')({
            url: cf.baseUrl + '/oauth/token',
            method: 'POST',
            header: {
                'Content-Type': 'application/x-www-form-urlencoded',
                Authorization: cf.baseAuth
            },
            data: {
                'grant_type': 'client_credentials'
            }
        }).then((res) => {
            let tokenInfo = res.data
            const now = new Date().getTime()
            const expiresIn = now + (tokenInfo.expires_in - 20) * 1000 // 过期时间，因网络延迟等，将实际过期时间提前20秒，以防止临界点
            tokenInfo.expires_in = expiresIn
            util.session(cf.LOCAL_TOKEN, tokenInfo)
            resolve(tokenInfo)
        }).catch(error => {
            reject(error)
        })
    })
}

const request = async (options = {}) => {
    // 加载遮罩
    let {
        noStatus = false, // 默认显示loading
        mask = false, // 不显示遮罩
        loadingText
    } = options

    if (!noStatus) {
        wx.showLoading({
            title: loadingText || 'Loading...',
            mask: mask
        })
    }

    options.url = cf.baseUrl + cf.PREFIX + options.url

    // token过期情况处理
    const token = util.session(cf.LOCAL_TOKEN)
    // if (!isValidToken(token, 'access_token')) {
    //     token = await getToken()
    // }
    options.header = options.header || {}
    // options.header.Authorization = token.token_type + ' ' + token.access_token
    options.header.token = token

    // 上传图片
    if (options.filePath) {
        options.header = {
            'Content-Type': 'multipart/form-data'
        }
        options.name = 'file'
        options.formData = {
            filename: 'pic_' + new Date().getTime() + '.' + options.suffix
        }
        return wxAsyncWrap('uploadFile')(options)
    }
      
    return requestAsync(options)
}

export default request


